package com.zty.spring.cloud.service.Impl;

import java.io.IOException;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zty.spring.cloud.entity.WeatherResponse;
import com.zty.spring.cloud.service.WeatherDataService;


/**
 * WeatherDataService 实现.
 * 
 * @since 1.0.0 2017年11月22日
 * @author <a href="https://waylau.com">Way Lau</a> 
 */
@Service
public class WeatherDataServiceImpl implements WeatherDataService {
	private final static Logger logger = LoggerFactory.getLogger(WeatherDataServiceImpl.class);  
	private static final String WEATHER_URI = "http://wthrcdn.etouch.cn/weather_mini?";
	private static final Long Time_OUT = 1800L;


	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@Override
	public WeatherResponse getDataByCityId(String cityId) {
		String uri = WEATHER_URI + "citykey=" + cityId;
		return this.doGetWeahter(uri);
	}

	@Override
	public WeatherResponse getDataByCityName(String cityName) {
		String uri = WEATHER_URI + "city=" + cityName;
		return this.doGetWeahter(uri);
	}


	private WeatherResponse doGetWeahter(String uri) {
		String key =uri;
		ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
		ObjectMapper mapper = new ObjectMapper();
		WeatherResponse resp = null;
		String strBody = null;
		if(stringRedisTemplate.hasKey(key)) {
			strBody=opsForValue.get(key);
			logger.info("查到了缓存数据");
		}else {
			ResponseEntity<String> respString = restTemplate.getForEntity(uri, String.class);
			if (respString.getStatusCodeValue() == 200) {
				strBody = respString.getBody();
			}
			opsForValue.set(key, strBody, Time_OUT, TimeUnit.SECONDS);
			logger.info("not查到了缓存数据");
		}
		try {
			resp = mapper.readValue(strBody, WeatherResponse.class);
		} catch (IOException e) {
			logger.error("ERROR",e);
		}
		return resp;
	}

	@Override
	public void syncDateByCityId(String cityId) {
		String uri = WEATHER_URI + "citykey=" + cityId;
		getsyncDateByCityId(uri);
	}

	private void getsyncDateByCityId(String uri) {
		String key =uri;
		String strBody = null;
		ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
		// 调用服务接口来获取
		ResponseEntity<String> respString =restTemplate.getForEntity(uri, String.class);
		if(respString.getStatusCodeValue()==200) {
			strBody = respString.getBody();
		}
		opsForValue.set(key, strBody,Time_OUT , TimeUnit.SECONDS);

	}
}
